package cn.txun.csmall.gateway.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 网关过滤器必须实现一个接口GlobalFilter
 * 如果想定义多个过滤器执行顺序
 * 还有实现接口Ordered
 */
@Slf4j
@Component
public class MyFilter01 implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
     /*  //chain.filter()调用之前编写的逻辑代码，都属pre时间
        System.out.println("filter01执行了pre");
        //过滤器方向，执行后续的内容
        Mono<Void> result = chain.filter(exchange);//生成一个继续执行的过滤器后的Mono
        //chain.filter()调用之后编写的逻辑代码，都属post时间
        System.out.println("filter01执行了post");*/
        //处理请求参数，先要在过滤器拿到请求对象
        ServerHttpRequest request = exchange.getRequest();
        //通过request对象获取参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        List<String> list = queryParams.get("name");
        //判断参数是否存在
        if(list==null || list.size()==0){
            log.error("当前请求没有携带name参数");
        }else{
            log.info("当前请求携带了name参数：{}",list.get(0));
        }
        //获取响应对象，可以做出响应
        ServerHttpResponse response = exchange.getResponse();

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
